package org.ycb.ycbisgod.ycbwoxihuanni.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.ycb.ycbisgod.ycbwoxihuanni.dto.InfoDTO;
import org.ycb.ycbisgod.ycbwoxihuanni.entity.User;
import org.ycb.ycbisgod.ycbwoxihuanni.mapper.UserMapper;
import org.ycb.ycbisgod.ycbwoxihuanni.service.IUserService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.ycb.ycbisgod.ycbwoxihuanni.util.PageResult;
import org.ycb.ycbisgod.ycbwoxihuanni.vo.QueryPageBean;
import org.ycb.ycbisgod.ycbwoxihuanni.vo.UserVo;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void register(String username, String password) {
        String encode = bCryptPasswordEncoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(encode);
        userMapper.insert(user);
    }

    @Override
    public User login(String username, String password) {
        User user = findByUsername(username);
        if (user != null && bCryptPasswordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    public PageResult<User> findPage(QueryPageBean queryPageBean) {
        log.info("查询用户列表，当前页: {}, 每页大小: {}, 查询条件: {}",
                queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());

        Page<User> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 默认按ID降序排序
        queryWrapper.orderByDesc(User::getId);

        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return new PageResult<>(userPage.getTotal(), userPage.getRecords());
    }

    public User findByUsername(String username) {
        return baseMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }


    /**
     * 根据用户名获取用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public User getUserInfo(String userName) {
        User user = userMapper.getUserInfo(userName);
        if (user == null) {
            log.warn("用户 {} 不存在", userName);
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }


    /**
     * 编辑用户信息
     *
     * @param infoDTO
     */
    @Override
    public void updateUserInfo(InfoDTO infoDTO) {
        //验证ID不为空
        if (ObjectUtils.isNull(infoDTO.getId())) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        //检查用户是否存在（
        User existingUser = baseMapper.selectById(infoDTO.getId()); // 使用ID查询
        if (existingUser == null) {
            log.warn("更新失败：用户ID {} 不存在", infoDTO.getId());
            throw new UsernameNotFoundException("用户不存在");
        }

        User user = new User();
        user.setId(infoDTO.getId());
        user.setUsername(infoDTO.getUsername());
        user.setPassword(bCryptPasswordEncoder.encode(infoDTO.getPassword()));
        userMapper.setUserInfo(user);
    }
}

